﻿using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace viBook.ModelBinders
{
    public class ImageUploadModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var fileData = controllerContext.HttpContext.Request.Files[0];
            if (fileData != null && fileData.ContentLength > 0)
            {
                var name = Path.GetFileName(fileData.FileName);
                if (!string.IsNullOrEmpty(name))
                {
                    string fileName = new Regex(@"\s+").Replace(name, "_"); // Change all whitespace into '_' charater
                    return new { FileName = fileName, FileData = fileData };
                }
            }
            return new { FileName = string.Empty, FileData = fileData };
        }
    }
}